package org.springblade.modules.admin.task;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.admin.entity.Elevator;
import org.springblade.modules.admin.entity.ElevatorContract;
import org.springblade.modules.admin.entity.ElevatorExt;
import org.springblade.modules.admin.entity.MaintainPlanConfig;
import org.springblade.modules.admin.enums.ElevatorMaintainStatusEnums;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.vo.contract.ContractElevatorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zcc
 * @version 1.0
 * @date 2025/8/19 14:25
 */

@Component
@Slf4j
public class ElevatorJob {

	@Autowired
	private IElevatorContractService elevatorContractService;

	@Autowired
	private ElevatorService elevatorService;

	@Autowired
	private IMaintainPlanConfigService maintainPlanConfigService;

	@Autowired
	private IBuildingUserContractService buildingUserContractService;

	@Autowired
	private IBuildingContractPlusService buildingContractPlusService;

	@Autowired
	private IElevatorExtService elevatorExtService;

	/**
	 * 更新项目的合同统计信息
	 */
	@XxlJob(value = "updateBuildingUserContract")
	public void updateBuildingUserContract() {
		buildingUserContractService.buildingUserContractJob();
	}


	/**
	 * 定时更新电梯---是否存在问题，是否存在断档
	 */
	@XxlJob(value = "updateElevatorstatus")
	public void updateElevatorstatus() {
		Map<Long, List<Elevator>> eleMaps = elevatorService.list().stream().collect(Collectors.groupingBy(Elevator::getId));
		List<ElevatorContract> listAll = elevatorContractService.getListAll(null);
		List<Long> elevatorIds = listAll.stream().map(ElevatorContract::getElevatorId).distinct().collect(Collectors.toList());
		Map<Long, List<ElevatorContract>> listMap = listAll.stream().collect(Collectors.groupingBy(ElevatorContract::getElevatorId));
		List<Elevator> updateList = new ArrayList<>(16);
		for (Long elevatorId : elevatorIds) {
			List<Elevator> elevators = eleMaps.get(elevatorId);
			if (elevators == null || elevators.size() == 0) {
				continue;
			}
			Elevator elevator = elevators.get(0);
			List<ElevatorContract> elevatorContracts = listMap.get(elevatorId);
			elevatorContracts = beginTimeAsc(elevatorContracts);
			Integer isGap = 0;
			Integer isQuestion = 0;
			for (int i = 0; i < elevatorContracts.size(); i++) {
				//当前合同
				ElevatorContract nowContract = elevatorContracts.get(i);
				//下一份合同
				Integer j = i;
				if (j < elevatorContracts.size() - 1) {
					j = j + 1;
				}
				ElevatorContract nextContract = elevatorContracts.get(j);
				if (nowContract.getContractId().equals(nextContract.getContractId())) {
					continue;
				}
				long days = DateUtil.betweenDay(nowContract.getContractEndTime(), nextContract.getContractBeginTime(), true);
				if (days > 1) {
					isGap = isGap + 1;
				}
			}
			if (isGap > 0) {
				isQuestion = 1;
			}
			if (elevator.getIsGap() != isGap || elevator.getIsQuestion() != isQuestion) {
				elevator.setIsGap(isGap);
				elevator.setIsQuestion(isQuestion);
				updateList.add(elevator);
			}
		}

		//更新电梯
		if (updateList.size() > 0) {
			for (List<Elevator> elevators : Lists.partition(updateList, 20)) {
				elevatorService.updateBatchById(elevators);
			}
		}
	}


	/**
	 * 更新电梯- 是否存在问题，
	 */
	@XxlJob(value = "updateElevatorQuestion")
	public void updateElevatorQuestion() {
		Map<Long, List<MaintainPlanConfig>> listMap = maintainPlanConfigService.list().stream().collect(Collectors.groupingBy(MaintainPlanConfig::getElevatorId));
		List<Elevator> list = elevatorService.list();
		List<Elevator> updateList = new ArrayList<>(16);
		for (Elevator elevator : list) {
			List<MaintainPlanConfig> maintainPlanConfigs = listMap.get(elevator.getId());
			if (maintainPlanConfigs == null || maintainPlanConfigs.size() == 0) {
				continue;
			}
			MaintainPlanConfig maintainPlanConfig = maintainPlanConfigs.get(0);
			Integer isQuestion = 0;
			if (maintainPlanConfig.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END.getId() || maintainPlanConfig.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_STOP.getId() || maintainPlanConfig.getMaintainStatus() == ElevatorMaintainStatusEnums.OUT_TIME_END_HAS_NEXT.getId()) {
				isQuestion = 1;
			}
			if (elevator.getIsQuestion() != isQuestion && Convert.toInt(elevator.getIsGap(), 0) == 0) {
				elevator.setIsQuestion(isQuestion);
				updateList.add(elevator);
			}
		}
		if (updateList.size() > 0) {
			for (List<Elevator> elevators : Lists.partition(updateList, 20)) {
				elevatorService.updateBatchById(elevators);
			}

		}
	}


	/**
	 * 更新电梯的重夺状态
	 */
	@XxlJob(value = "updateElevatorRegainStatus")
	public void updateElevatorRegainStatus() {
		List<ElevatorContract> listAll = elevatorContractService.getListAll(null);
		List<Long> elevatorIds = listAll.stream().map(ElevatorContract::getElevatorId).distinct().collect(Collectors.toList());
		Map<Long, List<ElevatorContract>> listMap = listAll.stream().collect(Collectors.groupingBy(ElevatorContract::getElevatorId));
		Map<Long, List<Elevator>> eleMaps = elevatorService.list().stream().collect(Collectors.groupingBy(Elevator::getId));


		List<Elevator> updateList = new ArrayList<>(16);
		for (Long elevatorId : elevatorIds) {
			List<Elevator> elevators = eleMaps.get(elevatorId);
			if (elevators == null || elevators.size() == 0) {
				continue;
			}
			Elevator elevator = elevators.get(0);
			Integer anInt = Convert.toInt(elevator.getRegainStatus(), -1);
			if (anInt == -1) {
				elevator.setRegainStatus(0);
			}
			List<ElevatorContract> elevatorContracts = listMap.get(elevatorId);
			elevatorContracts = beginTimeAsc(elevatorContracts);
			if (elevatorContracts.size() == 1) {
				Integer contractExtStatus = elevatorContracts.get(0).getContractExtStatus();
				if (contractExtStatus != 4) {
					//不等于脱保,重夺状态 --
					elevator.setRegainStatus(3);
				}
				if (contractExtStatus == 4) {
					//重夺状态为 未重夺
					elevator.setRegainStatus(2);
				}
			} else {
				//查找今天以前的合同 和今天以后的合同
				List<ElevatorContract> beforeContracts = elevatorContracts.stream().filter(t -> t.getContractEndTime().before(new Date())).collect(Collectors.toList());
				List<ElevatorContract> afterContracts = elevatorContracts.stream().filter(t -> t.getContractBeginTime().after(new Date())).collect(Collectors.toList());

				if (beforeContracts.size() == 0) {
					elevator.setRegainStatus(3);
					continue;
				}
				if (afterContracts.size() == 0) {
					elevator.setRegainStatus(2);
					continue;
				}
				if (beforeContracts.stream().map(ElevatorContract::getContractExtStatus).collect(Collectors.toList()).contains(4)) {
					elevator.setRegainStatus(1);
				}
			}

			if (anInt == -1 || anInt != elevator.getRegainStatus()) {
				updateList.add(elevator);
			}
		}

		if (updateList.size() > 0) {
			for (List<Elevator> elevators : Lists.partition(updateList, 20)) {
				elevatorService.updateBatchById(elevators);
			}
		}
	}


	/**
	 * 更新电梯的客户单位 和使用单位
	 */
	@XxlJob(value = "updateElevatorBuildingUser")
	public void updateElevatorBuildingUser() {
		//更新使用单位--没有新增，有更新
		List<MaintainPlanConfig> epibolyList = maintainPlanConfigService.list();
		List<ContractElevatorVo> contractElevatorVoList = buildingContractPlusService.getContractElevator();
		Map<Long, List<ContractElevatorVo>> longListMap = contractElevatorVoList.stream().collect(Collectors.groupingBy(ContractElevatorVo::getId));
		Map<Long, List<ElevatorExt>> listMap = elevatorExtService.list().stream().collect(Collectors.groupingBy(ElevatorExt::getElevatorId));
		List<ElevatorExt> updateList = new ArrayList<>(16);
		for (MaintainPlanConfig maintainPlanConfig : epibolyList) {
			List<ContractElevatorVo> contractElevatorVos = longListMap.get(maintainPlanConfig.getFromTypeContractId());
			List<ElevatorExt> elevatorExts = listMap.get(maintainPlanConfig.getElevatorId());
			ElevatorExt elevatorExt = elevatorExts == null || elevatorExts.size() == 0 ? new ElevatorExt() : elevatorExts.get(0);
			elevatorExt.setElevatorId(maintainPlanConfig.getElevatorId());
			elevatorExt.setTenantId(maintainPlanConfig.getTenantId());
			if (contractElevatorVos == null || contractElevatorVos.size() == 0) {
				elevatorExt.setBuildingUserName("-1");
				elevatorExt.setBuildingUserId(-1L);
				elevatorExt.setElevatorUserId(-1L);
			} else {
				ContractElevatorVo contractElevatorVo = contractElevatorVos.get(0);
				elevatorExt.setBuildingUserName(contractElevatorVo.getCustomerUnit());
				elevatorExt.setBuildingUserId(contractElevatorVo.getCustomerUnitId());
				elevatorExt.setElevatorUserId(contractElevatorVo.getElevatorCustomerUnitId());
			}
			updateList.add(elevatorExt);
		}
		List<List<ElevatorExt>> partition = Lists.partition(updateList, 20);
		for (List<ElevatorExt> elevatorExts : partition) {
			elevatorExtService.updateBatchById(elevatorExts);
		}
	}

	/**
	 * 创建时间升序
	 *
	 * @return
	 */
	private List<ElevatorContract> beginTimeAsc(List<ElevatorContract> elevatorContracts) {
		elevatorContracts = elevatorContracts.stream().sorted(new Comparator<ElevatorContract>() {
			@Override
			public int compare(ElevatorContract o1, ElevatorContract o2) {
				Date d1 = o1.getContractBeginTime();
				Date d2 = o2.getContractBeginTime();
				return d1.compareTo(d2);
			}
		}).collect(Collectors.toList());

		return elevatorContracts;
	}

}
